<template>
	<div class="upload-files-box">
		<el-upload
			action="#"
			class="upload-files"
			v-model:file-list="fileList"
			:multiple="true"
			:disabled="self_disabled"
			:limit="limit"
			:http-request="handleHttpUpload"
			:before-upload="beforeUpload"
			:on-exceed="handleExceed"
			:on-success="uploadSuccess"
			:on-error="uploadError"
			:accept="fileType.join(',')">
    	<el-button type="primary">上传</el-button>
		</el-upload>
		<div class="el-upload__tip">
			<slot name="tip"></slot>
		</div>
	</div>
</template>

<script setup lang="ts" name="UploadImgMultiple">
import { ref, computed, inject } from "vue";
import { generateUUID } from "@/utils/util";
import { useUpload } from "@/hooks/useUpload";
import type { UploadProps, UploadFile, UploadUserFile, UploadRequestOptions } from "element-plus";
import { ElNotification, formContextKey, formItemContextKey } from "element-plus";

type FileTypes =
	| "image/*" // 所有图片类型	PNG, JPEG, GIF, BMP, WebP, SVG等
	| "video/*" // 所有视频类型	MP4, WebM, AVI, MOV, MKV等
	| "audio/*" // 所有音频类型	MP3, WAV, OGG, AAC等
	| "application/pdf" // PDF文档
	| "text/*" // 所有文本类型	TXT, HTML, CSS, CSV等
	| "application/vnd.ms-excel" // EXCEL表格 xls
	| "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" // EXCEL表格 xlsx
	| "application/msword" // WORD文档 doc
	| "application/vnd.openxmlformats-officedocument.wordprocessingml.document" // WORD文档 docx
	| "application/vnd.ms-powerpoint" // PPT文件 ppt
	| "application/vnd.openxmlformats-officedocument.presentationml.presentation" // PPT文件 pptx
	| "application/zip" // ZIP文件
	| "application/x-rar-compressed" // RAR文件
	| "application/x-7z-compressed" // 7z文件

interface UploadFileProps {
	fileList: UploadUserFile[];
	api?: (params: any) => Promise<any>; // 上传图片的 api 方法，一般项目上传都是同一个 api 方法，在组件里直接引入即可 ==> 非必传
	drag?: boolean; // 是否支持拖拽上传 ==> 非必传（默认为 true）
	disabled?: boolean; // 是否禁用上传组件 ==> 非必传（默认为 false）
	limit?: number; // 最大图片上传数 ==> 非必传（默认为 5张）
	fileSize?: number; // 图片大小限制 ==> 非必传（默认为 5M）
	fileType?: FileTypes[]; // 图片类型限制 ==> 非必传
	height?: string; // 组件高度 ==> 非必传（默认为 150px）
	width?: string; // 组件宽度 ==> 非必传（默认为 150px）
	borderRadius?: string; // 组件边框圆角 ==> 非必传（默认为 8px）
}

const props = withDefaults(defineProps<UploadFileProps>(), {
	fileList: () => [],
	drag: true,
	disabled: false,
	limit: 5,
	fileSize: 5,
	fileType: () => [],
	height: "150px",
	width: "150px",
	borderRadius: "8px"
});
// 生成组件唯一id
const uuid = ref("id-" + generateUUID());
// 获取 el-form 组件上下文
const formContext = inject(formContextKey, void 0);
// 获取 el-form-item 组件上下文
const formItemContext = inject(formItemContextKey, void 0);
// 判断是否禁用上传和删除
const self_disabled = computed(() => {
	return props.disabled || formContext?.disabled;
});

const fileList = ref<UploadUserFile[]>(props.fileList);
/**
 * @description 文件上传之前判断
 * @param rawFile 上传的文件
 * */
const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
	const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
	const imgType = props.fileType;
	// 通用类型校验
	const mimeType = rawFile.type.split('/')[0] + '/*'

	if (imgType.length > 0 && !imgType.includes(rawFile.type as FileTypes) && !imgType.includes(mimeType as FileTypes))
		ElNotification({
			title: "温馨提示",
			message: "上传文件不符合所需的格式！",
			type: "warning"
		});
	if (!imgSize)
		ElNotification({
			title: "温馨提示",
			message: `上传文件大小不能超过 ${props.fileSize}M！`,
			type: "warning"
		});

	return (imgType.length <= 0 || (imgType.length > 0 && (imgType.includes(rawFile.type as FileTypes) || imgType.includes(mimeType as FileTypes)))) && imgSize
};

/**
 * @description 图片上传
 * @param options 上传的文件
 * */
const handleHttpUpload = async (options: UploadRequestOptions) => {
  const { _upload } = useUpload(options);
  const fileUrl: any = await _upload()
  options.onSuccess({fileUrl});
};

// 图片上传成功
interface UploadEmits {
	(e: "update:fileList", value: UploadUserFile[]): void;
}
const emit = defineEmits<UploadEmits>();
const uploadSuccess = (response: { fileUrl: string } | undefined, uploadFile: UploadFile) => {
	if (!response) return;
	uploadFile.url = response.fileUrl;
	emit("update:fileList", fileList.value);
	// 调用 el-form 内部的校验方法（可自动校验）
	formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
	ElNotification({
		title: "温馨提示",
		message: "上传成功！",
		type: "success"
	});
};

// 文件上传错误提示
const uploadError = () => {
	ElNotification({
		title: "温馨提示",
		message: "文件上传失败，请您重新上传！",
		type: "error"
	});
};

// 文件数超出提示
const handleExceed = () => {
	ElNotification({
		title: "温馨提示",
		message: `当前最多只能上传 ${props.limit} 个文件，请移除后上传！`,
		type: "warning"
	});
};
</script>

<style scoped lang="scss">
.upload-files-box {
	.el-upload__tip {
		line-height: 15px;
		text-align: center;
	}
}
</style>
